package controller

import (
	"encoding/json"
	"io/ioutil"
	"kingbloc.dts/models"
	"kingbloc.dts/services"
	"kingbloc.dts/tools"
	"kingbloc.sso/user"
	"kingbloc.util/util"
	"net/http"
	"strings"
)

type DtsInfo struct {
	Order          []*model.Orderr
	Account        *model.Account
	IntroducerUser *user.User // 我的推荐人信息
	AmountAward    map[int64]*model.AmountAward
	MyRecommended  []*model.Orderr `json:"myRecommended"`
}

func MyAccount(rep http.ResponseWriter, req *http.Request) {

	userA := validateUserInfo(req)

	if userA == nil {
		rep.WriteHeader(403)
		return
	}

	myAccount := model.FindAccountBySsoId(userA.Id)

	if myAccount == nil || myAccount.Id == 0 {
		rep.WriteHeader(403)
		return
	}

	myOrders := model.NewOrder().ByAccountId(myAccount.Id)

	if len(myOrders) == 0 {
		util.WriteJSON(rep, 0)
		return
	}

	myRecommendeds := service.MyRecommended(myAccount.Id)

	amountAwards := map[int64]*model.AmountAward{}

	for _, v := range myOrders {
		aa := service.AmountAwardByOrderId(v.Id)
		if aa != nil {
			amountAwards[v.Id] = aa
		}
	}

	var introducerUser *user.User = userA
	if myOrders[0].IntroducerId != 0 {
		introducerAccount := service.FindAccountById(myOrders[0].IntroducerId)
		introducerUser = tool.UserInfoById(introducerAccount.SsoUserId)
	}

	dtsInfo := &DtsInfo{
		Order:          myOrders,
		Account:        myAccount,
		IntroducerUser: introducerUser,
		AmountAward:    amountAwards,
		MyRecommended:  myRecommendeds,
	}

	util.WriteJSON(rep, dtsInfo)

}

func UpdatePwd2(rep http.ResponseWriter, req *http.Request) {

	if strings.ToLower(req.Method) != "post" {
		rep.WriteHeader(200)
		return
	}

	user := validateUserInfo(req)

	if user == nil {
		rep.WriteHeader(200)
		return
	}

	//
	var result map[string]string
	bp, err1 := ioutil.ReadAll(req.Body)
	util.CheckErr(err1)
	err2 := json.Unmarshal(bp, &result)
	util.CheckErr(err2)

	pwd2 := result["pwd2"]

	if pwd2 == "" || len(pwd2) > 8 {
		rep.WriteHeader(200)
		return
	}

	myAccount := service.FindAccountBySSOId(user.Id)

	if myAccount == nil || myAccount.Id == 0 {
		rep.WriteHeader(200)
		return
	}

	myOrders := service.FindOrdersByAccountId(myAccount.Id)
	var myOrder *model.Orderr
	if len(myOrders) > 0 {
		myOrder = myOrders[0]
	}

	if myOrder.IntroducerId == 0 {
		rep.WriteHeader(200)
		return
	}

	pwd2ClientTmp := util.Md5EncodeForPassword(pwd2)
	approve := model.NewApprove()
	approve.ExaminerAccountId = myOrder.IntroducerId
	approve.ProposerAccountId = myAccount.Id
	approve.ProposerAccountMob = user.Mobile
	approve.Types = 0
	approve.Status = 0
	approve.DataContent = pwd2ClientTmp
	approve.Add()

	//fmt.Printf("%+v\n", approve)

	util.WriteJSON(rep, 2)

}

func UpdatePwd1(rep http.ResponseWriter, req *http.Request) {

	if strings.ToLower(req.Method) != "post" {
		rep.WriteHeader(200)
		return
	}

	user := validateUserInfo(req)

	if user == nil {
		rep.WriteHeader(200)
		return
	}

	//
	var result map[string]string
	bp, err1 := ioutil.ReadAll(req.Body)
	util.CheckErr(err1)
	err2 := json.Unmarshal(bp, &result)
	util.CheckErr(err2)

	pwd1New := result["pwd1"]
	pwd2 := result["pwd2"]

	if pwd1New == "" || pwd2 == "" {
		rep.WriteHeader(200)
		return
	}

	myAccount := service.FindAccountBySSOId(user.Id)

	if myAccount == nil || myAccount.Id == 0 {
		rep.WriteHeader(200)
		return
	}

	pwd2ClientTmp := util.Md5EncodeForPassword(pwd2)
	if pwd2ClientTmp != myAccount.Password2 { // 二级密码与客户端临时提供的pwd2密码 不一致
		rep.WriteHeader(200)
		return
	}

	param := map[string]interface{}{}
	param["id"] = user.Id
	param["field"] = "password"
	param["value"] = pwd1New

	conf := tool.GetConfig()
	toUrl := conf.Get("sso", "url")
	toUrl += "/update"
	tokenObj, _ := req.Cookie("SSOTOKEN")
	dataStr := util.Post2(tokenObj.Value, toUrl, param)
	if dataStr == "" {
		util.WriteJSON(rep, 1)
		return
	}
	if strings.ToLower(dataStr) == "ok" {
		util.WriteJSON(rep, 2)
		return
	}

}
